<?php

class OrganizersController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(

		);
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Organizers;
		$o_profile = new OrganizerProfile ;
		$s_social = new OrganizerSocial ;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Organizers'],$_POST['OrganizerProfile'],$_POST['OrganizerSocial']))
		{
			$model->attributes=$_POST['Organizers'];
			$model->attributes=$_POST['OrganizerProfile'];
			$model->attributes=$_POST['OrganizerSocial'];

			if(isset($_POST['Organizers']['district_id'])){
				$district = Districts::model()->findByPk($_POST['Organizers']['district_id']);
				$model->district = $district->cname;
			}
			if(isset($_POST['Organizers']['city_id'])){
				$city = Cities::model()->findByPk($_POST['Organizers']['city_id']);
				$model->city = $city->name;
			}
			if(isset($_POST['Organizers']['country_id'])){
				$country = Countries::model()->findByPk($_POST['Organizers']['country_id']);
				$model->country = $country->name;
			}
			if(CUploadedFile::getInstance($model,'image') != null){
				$model->image = CUploadedFile::getInstance($model,'image');
		        $image = $this->createSlug($_POST['Organizers']['title']) .'-'. time() . '.' . $model->image->getExtensionName();
		        $model->image->saveAs(IMAGES_DIR.'/Organizers/' . $image);
		        //save image load curent in folder images
		        $model->image = $image;
		        $model->url = $this->createSlug($model->title);
		        $model->createddate = date("d-m-Y H:i:s");
				if($model->validate()){ 
					$model->save(false) ;
					$o_profile->description = $_POST['OrganizerProfile']['description'];
					$o_profile->organizer_id = $model->id;
					$o_profile->save();
					foreach($_POST['OrganizerSocial']['social_id'] as $k=>$data)
                    {
		                    $addsocial = new OrganizerSocial;  
		                    $addsocial->social_id = $_POST["OrganizerSocial"]['social_id'][$k];
		                    $addsocial->url = $_POST["OrganizerSocial"]['url'][$k];
		                    $addsocial->organizer_id = $model->id;
		                    $addsocial->save() ;
                	}

					$this->redirect(array('view','id'=>$model->id));
				}
			}else{
		        Yii::app()->user->setFlash('error',"<b>Bạn chưa chọn hình ảnh.<b/>");
		     }
			
		}

		$this->render('create',array(
			'model'=>$model,'o_profile'=>$o_profile,'s_social'=>$s_social,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$currentImage = $model->image ;
		$s_social =OrganizerSocial::model()->findAllByAttributes(array('organizer_id'=>$id));
		if(empty($s_social)){
			$s_social = new OrganizerSocial ;
		}
		$o_profile =OrganizerProfile::model()->findByAttributes(array('organizer_id'=>$id));
		if(empty($o_profile)){
			$o_profile = new OrganizerProfile;
		}
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Organizers']))
		{
				$model->attributes=$_POST['Organizers'];
				if(isset($_POST['Organizers']['district_id'])){
					$district = Districts::model()->findByPk($_POST['Organizers']['district_id']);
					$model->district = $district->cname;
				}
				if(isset($_POST['Organizers']['city_id'])){
					$city = Cities::model()->findByPk($_POST['Organizers']['city_id']);
					$model->city = $city->name;
				}
				if(isset($_POST['Organizers']['country_id'])){
					$country = Countries::model()->findByPk($_POST['Organizers']['country_id']);
					$model->country = $country->name;
				}
				if(CUploadedFile::getInstance($model,'image') != null){
					$model->image = CUploadedFile::getInstance($model,'image');
			        $image = 'Organizers' . time() . '.' . $model->image->getExtensionName();
			        $model->image->saveAs(IMAGES_DIR.'/organizers/' . $image);
			        //save image load curent in folder images
			        $model->image = $image;
			    }else{
			    	$model->image = $currentImage ;
			    }
					if($model->validate()){
						$model->save();
						$o_profile->description = $_POST['OrganizerProfile']['description'];
						$o_profile->organizer_id = $model->id;
						$o_profile->save(); 
						foreach($_POST['OrganizerSocial']['social_id'] as $k=>$data)
                    	{
		                    $addsocial = new OrganizerSocial;  
		                    $addsocial->social_id = $_POST["OrganizerSocial"]['social_id'][$k];
		                    $addsocial->url = $_POST["OrganizerSocial"]['url'][$k];
		                    $addsocial->organizer_id = $model->id;
		                    $addsocial->save() ;
                		}

						$this->redirect(array('view','id'=>$model->id));
					}
		  }

		$this->render('update',array(
			'model'=>$model,'o_profile'=>$o_profile,'s_social'=>$s_social,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();
        $criteria = new CDbCriteria;
        $criteria->condition='organizer_id='.$id;
        OrganizerProfile::model()->deleteAll($criteria);
        OrganizerSocial::model()->deleteAll($criteria);
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

	public function actionView($id){
		if(isset($id)){
			$model = Organizers::model()->findByPk($id);
			$profile = OrganizerProfile::model()->findByAttributes(array('organizer_id'=>$id));
			$social = OrganizerSocial::model()->findAllByAttributes(array('organizer_id'=>$id));
			$this->render('view',array('model'=>$model,'profile'=>$profile,'social'=>$social));
		}
		
	}
	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new Organizers('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Organizers']))
			$model->attributes=$_GET['Organizers'];

		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Organizers the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Organizers::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Organizers $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='organizers-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
